﻿using BusinessService.Plugin.DataSource.Sqlite.Dtos;
using BusinessService.Plugin.Entity;
using BusinessService.Plugin.Helper;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.VisualBasic.FileIO;
using MQTTnet.Server;
using SqlSugar;
using SqlSugar.Extensions;
using SqlSugarRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
namespace BusinessService.Plugin.DataSource.Sqlite
{
    /// <summary>
    /// sqlite方法库
    /// </summary>
    public class SqliteLibrary
    {
        private readonly SqlSugarRepository<ParameterSettings> _repParam;
        private readonly SqlSugarRepository<FilterTable> _repFilter;
        private readonly SqlSugarRepository<SelectFields> _repSelect;
        private readonly SqlSugarRepository<JsonStruct> _repStruct;
        private readonly SqlSugarRepository<JsonBuildEntity> _repBuild;
        private readonly SqlSugarRepository<AllSet> _repSet;
        public SqliteLibrary(
            SqlSugarRepository<ParameterSettings> repParam
            , SqlSugarRepository<SelectFields> repSelect
            , SqlSugarRepository<FilterTable> repFilter
            , SqlSugarRepository<JsonBuildEntity> repBuild
           , SqlSugarRepository<JsonStruct> repStruct
            , SqlSugarRepository<AllSet> repSet
            )
        {
            _repParam = repParam;
            _repFilter = repFilter;
            _repSelect = repSelect;
            _repBuild = repBuild;
            _repStruct = repStruct;
            _repSet = repSet;
        }
        /// <summary>
        /// 更新事件通知窗体界面
        /// </summary>
        public event Action UpdateEvent;
        /// <summary>
        /// 错误事件通知
        /// </summary>
        public event Action<string> ErrorEvent;

        /// 创建sqlite数据库表(初始化执行)
        /// </summary>
        /// <param name="args"></param>
        public void CreateSqlite()
        {
            try
            {
              
                SqlSugarScopeProvider childDB;
                childDB = _repParam.Context.AsTenant().GetConnectionScope("1");//线程安全用GetConnectionScope
                var result = childDB.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库    
                childDB.CodeFirst.InitTables<SelectFields, FilterTable, ParameterSettings, JsonBuildEntity, AllSet>();      //建参数设置主表ParameterSettings,

            }
            catch (Exception)
            {
                throw;
            }
        }



        /// <summary>
        /// 获取所有的表格名称
        /// </summary>
        /// <returns></returns>
        public List<string> GetTableInfoList()
        {
            var tables = _repParam.Context.DbMaintenance.GetTableInfoList(false).Select(x => x.Name).ToList();//   获取表名true 走缓存 false不走缓存
            return tables;
        }
        /// <summary>
        /// 获取选定表格的字段信息
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public List<DbColumnInfo> GetColumnInfosByTableName(string args)
        {
            try
            {

       
            var fields = _repParam.Context.DbMaintenance.GetColumnInfosByTableName(args);//获取字段名 缓存 false不走缓存
            return fields;
            }
            catch (Exception)
            {

                return new List<DbColumnInfo>();
            }
        }
        #region 数据源定义操作
        /// <summary>
        /// 查询Sqlite主表数据
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public List<ParameterSettings> sqliteQuery()
        {
            //查表
            try
            {
                var param = _repParam.AsQueryable().ToList();
                return param;

            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// 查询Sqlite主表数据
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public ParameterSettings sqliteQuery(long input)
        {
            //查表
            try
            {
                var param = _repParam.AsQueryable().Where(p => p.ID == input).First();
                return param;

            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 数据库配置联合查询
        /// </summary>
        /// <returns></returns>
        public SqliteLibraryOutput jointQuery(long input)
        {
            //查表
            try
            {
                if (SqlFunc.IsNullOrEmpty(input)) return null;
                SqliteLibraryOutput Output = new SqliteLibraryOutput();
                Output.P = _repParam.Where(p => p.ID == input).First();
                Output.F = _repFilter.Where(p => p.P_Id == input).ToList();
                Output.S = _repSelect.Where(p => p.P_Id == input).ToList();
                return Output;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 向数据源列表 插入一条记录
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void SqliteInsert(SqliteLibraryInput input)
        {
            try
            {
                if (_repParam.Any(x => x.Name.Equals(input.mainTable.Name)))
                {
                    if (ErrorEvent!=null)
                    {
                        ErrorEvent("已存在相同名称的数据源！");
                        return;
                    }
                }
              

                _repParam.BeginTran();
                if (input.mainTable.V_ProtocolType.Equals("DataBase"))
                {
                    input.mainTable.ID = SnowIdUtil.GetId();
                    var pId = _repParam.InsertReturnSnowflakeId(input.mainTable);
                    input.whereEx.ForEach(p => { p.ID = SnowIdUtil.GetId(); p.P_Id = pId; });
                    if (input.whereEx.Count>0)
                    {
                        _repFilter.Insert(input.whereEx);
                    }
                    input.SelectFields.ForEach(p => { p.ID = SnowIdUtil.GetId(); p.P_Id = pId; });
                    if (input.SelectFields.Count > 0)
                    {
                        _repSelect.Insert(input.SelectFields);
                    }
                }
                else
                {
                    input.mainTable.ID = SnowIdUtil.GetId();
                    _repParam.Insert(input.mainTable);   //Socket/mqtt/HTTP新增数据
                }

                _repParam.CommitTran();
          
            }
            catch (Exception e)
            {
                _repParam.RollbackTran();

                throw e;
          
            }
        }
        /// <summary>
        /// 向Sqlite更新一条记录
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void SqliteUpdate(SqliteLibraryInput input)
        {
            try
            {
                if (_repParam.Any(x => x.Name.Equals(input.mainTable.Name) && x.ID != input.mainTable.ID))
                {
                    if (ErrorEvent != null)
                    {
                        ErrorEvent("已存在相同名称的数据源！");
                        return;
                    }
                }


                _repParam.BeginTran();
                if (input.mainTable.V_ProtocolType.Equals("DataBase"))
                {
                    var pId = input.mainTable.ID;
                    _repParam.Update(input.mainTable);
                    _repFilter.Delete(x => x.P_Id == pId);
                    input.whereEx.ForEach(p => { p.ID = SnowIdUtil.GetId(); p.P_Id = pId; });
                    if (input.whereEx.Count > 0)
                    {
                        _repFilter.Insert(input.whereEx);
                    }
                    _repSelect.Delete(x => x.P_Id == pId);
                    input.SelectFields.ForEach(p => { p.ID = SnowIdUtil.GetId(); p.P_Id = pId; });
                    if (input.SelectFields.Count > 0)
                    {
                        _repSelect.Insert(input.SelectFields);
                    }
                }
                else
                {
                    _repParam.Update(input.mainTable);   //Socket/mqtt/HTTP更新数据
                }
                _repParam.CommitTran();
            }
            catch (Exception)
            {
                _repParam.RollbackTran();
                throw;
            }
        }
        /// <summary>
        /// 删除一条主表数据
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void sqliteDelete(long ID)
        {
            //删除一条记录
            try
            {
                _repParam.BeginTran();
                _repParam.Delete(x => x.ID.Equals(ID));
                _repFilter.Delete(x => x.P_Id.Equals(ID));
                _repSelect.Delete(x => x.P_Id.Equals(ID));
                _repParam.CommitTran();
            }
            catch (Exception)
            {
                _repParam.RollbackTran();
                throw;
            }
        }


        #region  



        #endregion


        #region 和json数据组装有关的操作


        /// <summary>
        /// json主表插入、更新
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void JsonEdit(JsonBuildEntity input)
        {
            try
            {
                _repBuild.BeginTran();

                if (input.ID == 0)
                {

                    if (_repBuild.Any(x => x.Name.Equals(input.Name)))
                    {


                        return;
                    }


                    input.ID = SnowIdUtil.GetId();
                    _repBuild.Insert(input);
                }
                else
                {
                    _repBuild.Update(input);
                }
                _repBuild.CommitTran();
            }
            catch (Exception)
            {
                _repBuild.RollbackTran();
            }
        }







        /// <summary>
        /// Json主键查询
        /// </summary>
        /// <returns></returns>
        public JsonBuildEntity JsonStructQuery(long input)
        {
            //查表
            try
            {
                if (SqlFunc.IsNullOrEmpty(input)) return null;
                JsonOutput Output = new();
                var list = _repBuild.Where(p => p.ID == input).First();
                return list;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Json查询
        /// </summary>
        /// <returns></returns>
        public List<JsonBuildEntity> JsonQuery()
        {
            //查表
            try
            {
                return _repBuild.ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 删除一条Json组装的数据
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void jsonStructDelete(long ID)
        {
            //删除一条记录
            try
            {
                _repBuild.Delete(x => x.ID.Equals(ID));
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion




        #region 和所有参数设置有关的操作


        /// <summary>
        /// 协议参数设置全表插入、更新
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void AllSetEdit(AllSet input)
        {
            try
            {



                if (input.N_Id == 0)
                {

                    if (_repSet.Any(x => x.V_Name.Equals(input.V_Name)))
                    {
                        if (ErrorEvent != null)
                        {
                            ErrorEvent("已存在相同名称的参数设置，请立即修改！");
                            return;
                        }
                    }
                    input.N_Id = SnowIdUtil.GetId();
                    _repSet.Insert(input);
                }
                else
                {

                    if (_repSet.Any(x => x.V_Name.Equals(input.V_Name) && x.N_Id != input.N_Id))
                    {
                        if (ErrorEvent != null)
                        {
                            ErrorEvent("已存在相同名称的参数设置，请立即修改！");
                            return;
                        }
                    }
                    _repSet.Update(input);
                }

            }
            catch (Exception)
            {
                return;
            }
        }


        /// <summary>
        ///协议参数设置全表记录(查询)
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public List<AllSet> AllSetQuery(AllSetQueryInput input)
        {

            try
            {
                var list = _repSet.AsQueryable()
                          .WhereIF(input.N_Id > 0, x => x.N_Id.Equals(input.N_Id))
                          .WhereIF(input.N_Role > 0, x => x.N_Role.Equals(input.N_Role))
                          .WhereIF(!SqlFunc.IsNullOrEmpty(input.V_ProtocolType), x => x.V_ProtocolType.Equals(input.V_ProtocolType))
                          .ToList();

                return list;



            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取所有的通道名称
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public List<string> GetProtocolName()
        {
            //获取所有的通道名称
            try
            {
                return _repSet.AsQueryable().Where(x => x.N_Role.Equals(2)).Select(x => x.V_Name).ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取指定名称的通道类型
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public string GetProtocolType(string name)
        {
            //获取所有的通道名称
            try
            {
                if (name.IsNullOrEmpty()) return string.Empty;

                return _repSet.AsQueryable()
                        .Where(x => x.N_Role.Equals(2))
                         .Where(x => x.V_Name.Equals(name))
                        .Select(x => x.V_ProtocolType).First();
            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// 协议参数设置全表记录(删除记录)
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void AllSetDelete(long input)
        {
            //删除一条记录
            try
            {
                _repSet.Delete(x => x.N_Id.Equals(input));
            }
            catch (Exception)
            {
                throw;
            }
        }


        #endregion
    }
}
#endregion